const dbMod = require('./dbMod')
const async = require('async')
const fs = require('fs')
const replySQL = require('./replySQL')

function addnotice (userID, title, content, partitionID, time, callback) {
  let sql = 'INSERT INTO announcement (announcementUserID, announcementPartID, announcementTitle, announcementContent, announcementTime, announcementReplyTime) VALUES (?,?,?,?,?,?)'
  dbMod.query(sql, [userID, partitionID, title, content, time, time], (result) => {
    let sql2 = 'SELECT * FROM announcement WHERE announcementID=?'
    dbMod.query(sql2, [result.insertId], (result) => {
      var notice = eval(result)[0]
      let sql3 = 'SELECT * FROM `partition` WHERE partitionID=?'
      dbMod.query(sql3, [partitionID], (result) => {
        var partition = eval(result)[0]
        callback(notice, partition)
      })
    })
  })
}

function getnotice (partitionID, callback) {
  let sql1 = 'SELECT * FROM `partition` WHERE partitionID=?'
  dbMod.query(sql1, [partitionID], (result) => {
    var partition = eval(result)
    let sql2 = 'SELECT * FROM announcement WHERE announcementPartID=? ORDER BY announcementTime DESC'
    dbMod.query(sql2, [partitionID], (result) => {
      var announcements = eval(result)
      callback(partition, announcements)
    })
  })
}

function delnotice (postID, callback) {
  let sql1 = 'SELECT * FROM reply WHERE replyPostID=? AND isAnnouncement=1'
  dbMod.query(sql1, [postID], (result) => {
    var replies = eval(result)

    // 删除回帖Content文件
    var deleteFileTasks = []
    replies.forEach(reply => {
      function deleteFile (done) {
        fs.unlink(replySQL.dir + reply.replyContent, (err) => {
          if (err) {
            console.log(err)
            done(err, null)
          }
          else {
            console.log('deleted file: ' + reply.replyContent)
            done(null, null)
          }
        })
      }
      deleteFileTasks.push(deleteFile)
    });
    async.parallel(deleteFileTasks, (err, results) => {
      if (err) console.log(err)
      else {
        // 删除数据库回帖记录
        let sql2 = 'DELETE FROM reply WHERE replyPostID=? AND isAnnouncement=1'
        dbMod.query(sql2, [postID], (result) => {
          var result1 = eval(result)

          // 删除主帖content文件
          let sql3 = 'SELECT * FROM announcement WHERE announcementID=?'
          dbMod.query(sql3, [postID], (result) => {
            var filename = eval(result)[0].announcementContent
            fs.unlink(replySQL.dir + filename, (err) => {
              if (err) console.log(err)
              else {
                console.log('deleted file:' + filename)

                // 删除数据库主帖记录
                let sql4 = 'DELETE FROM announcement WHERE announcementID=?'
                dbMod.query(sql4, [postID], (result) => {
                  callback()
                })
              }
            })
          })
        })
      }
    })
  })

}

exports.addnotice = addnotice
exports.getnotice = getnotice
exports.delnotice = delnotice